package com.zhangye.test.cloud;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Param;
import org.asynchttpclient.Response;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.zhangye.test.cloud.Auth;
import com.zhangye.test.entity.EasyArResult;
import com.zhangye.test.entity.RemoveResult;
import com.zhangye.test.entity.SimilarResult;
import com.zhangye.test.model.EasyAr;

public class cloudUtil {
	
	private static final String HOST       = "http://6296c09052012b394de6c002d7b81508.cn1.crs.easyar.com:8888";
    private static final String APP_KEY    = "a1d3c25006629cf8e3bbabd0c64003dd";
    private static final String APP_SECRET = "kYSRElAeH4ceubOnGnBiMqyrHYUgspVHZqBcibifXD10ldVjwhU1RGRwebMjGsry7ItPyreLGBQfG5ZB6IzSKspVmhOeLGQ3ZkB08G7BPE9gSnZyLQiscnHiEOiBS5I8";


    static EasyArResult ear = new EasyArResult();
    /**
     * 添加
     * 作者： 张叶
     * 创建时间：2018年5月22日  下午3:44:43
     */
    public static EasyArResult addClouds(String file,String name,Integer size,String meta) throws JSONException, IOException, InterruptedException{
        AsyncHttpClient client = new DefaultAsyncHttpClient();
        JSONObject params = new JSONObject();
        params.put("image", file);
        params.put("active", "1");
        params.put("name", name);
        params.put("size", "20");
        params.put("meta", meta); 
        params.put("type","ImageTarget");
        Auth.signParam(params, APP_KEY, APP_SECRET);
        client.preparePost(HOST + "/targets/")
        .setBody(params.toString().getBytes())
        .execute(new AsyncCompletionHandler<Void>() {
            @Override
            public Void onCompleted(Response response) throws Exception {
                System.out.println(response.getResponseBody());
        		Gson gson = new Gson();
        		ear = gson.fromJson(response.getResponseBody(),EasyArResult.class);
                client.close();
                return null;
            }
        });
		Thread.sleep(8000);
        return ear;
    }
    
    static String result = "";
    
    /**
     * 修改
     * 作者： 张叶
     * 创建时间：2018年5月18日  上午9:16:13
     */
    public static EasyArResult updateCloud(EasyAr ea) throws Exception{
        AsyncHttpClient client = new DefaultAsyncHttpClient();

        JSONObject params = new JSONObject();
        params.put("active", ea.getActive().toString());
        params.put("name", ea.getName());
        params.put("size", "20");
		Auth.signParam(params, APP_KEY, APP_SECRET);
        client.preparePut(HOST + "/target/" + ea.getTargetId())
        .setBody(params.toString().getBytes())
        .execute(new AsyncCompletionHandler<Void>() {
            @Override
            public Void onCompleted(Response response) throws Exception {
                System.out.println(response.getResponseBody());
        		Gson gson = new Gson();
        		ear = gson.fromJson(response.getResponseBody(),EasyArResult.class);
                client.close();
                return null;
            }
        });
		Thread.sleep(5000);
        return ear;
    }

    
    /**
     * 修改
     * 作者： 张叶
     * 创建时间：2018年5月18日  上午9:16:13
     */
    public static EasyArResult updateCloud(String targetId,String meta) throws Exception{
        AsyncHttpClient client = new DefaultAsyncHttpClient();

        JSONObject params = new JSONObject();
        params.put("meta", meta); 
		Auth.signParam(params, APP_KEY, APP_SECRET);
        client.preparePut(HOST + "/target/" + targetId)
        .setBody(params.toString().getBytes())
        .execute(new AsyncCompletionHandler<Void>() {
            @Override
            public Void onCompleted(Response response) throws Exception {
                System.out.println(response.getResponseBody());
        		Gson gson = new Gson();
        		ear = gson.fromJson(response.getResponseBody(),EasyArResult.class);
                client.close();
                return null;
            }
        });
		Thread.sleep(5000);
        return ear;
    }
    
    
    
    /**
     * 根本targetId得到信息
     * 作者： 张叶
     * 创建时间：2018年5月10日  下午3:33:13
     */
	public static void getCloud(String targetId) {

		AsyncHttpClient client = new DefaultAsyncHttpClient();
		JSONObject params = new JSONObject();
		Auth.signParam(params, APP_KEY, APP_SECRET);

		client.prepareGet(HOST + "/target/" + targetId)
		.setQueryParams(toParams(params))
		.execute(new AsyncCompletionHandler<Void>() {
			@Override
			public Void onCompleted(Response response) throws Exception {
				System.out.println(response.getResponseBody());
				client.close();
				return null;
			}
		});
	}
	
	
	/**
	 * 根据targetId删除
	 * 作者： 张叶
	 * 创建时间：2018年5月10日  下午3:33:48
	 */
	static RemoveResult rr = new RemoveResult();
	public static RemoveResult removeCloud(String targetId) throws Exception {
		AsyncHttpClient client = new DefaultAsyncHttpClient();
		JSONObject params = new JSONObject();
		Auth.signParam(params, APP_KEY, APP_SECRET);
        client.prepareDelete(HOST + "/target/" + targetId)
                .setQueryParams(toParams(params))
                .execute(new AsyncCompletionHandler<Void>() {
                    @Override
                    public Void onCompleted(Response response) throws Exception {
                        System.out.println(response.getResponseBody());
                		Gson gson = new Gson();
                		rr = gson.fromJson(response.getResponseBody(),RemoveResult.class);
                        client.close();
                        return null;
                    }
                });
//		Thread.sleep(5000);
        return rr;
	}
	
	
	/**
	 * 相似目标图像 
	 * 作者： 张叶
	 * 创建时间：2018年5月10日  下午3:33:48
	 */
	static SimilarResult sr = new SimilarResult();
	public static SimilarResult similarCloud(String file) throws Exception {
		AsyncHttpClient client = new DefaultAsyncHttpClient();
		JSONObject params = new JSONObject();
        params.put("image", file);
		Auth.signParam(params, APP_KEY, APP_SECRET);
        client.preparePost(HOST + "/similar/")
            .setBody(params.toString().getBytes())
            .execute(new AsyncCompletionHandler<Void>() {
                @Override
                public Void onCompleted(Response response) throws Exception {
                    System.out.println(response.getResponseBody());
            		Gson gson = new Gson();
            		sr = gson.fromJson(response.getResponseBody(),SimilarResult.class);
                    client.close();
                    return null;
                }
            });
		Thread.sleep(5000);
        return sr;
	}

    private static List<Param> toParams(JSONObject jso) {
        return jso.keySet().stream()
                .map(key -> new Param(key, jso.getString(key)))
                .collect(Collectors.toList());
    }
}
